import socket


def log(*args, **kwargs):
    print('log', *args, **kwargs)


def route_index():
    header = 'HTTP/1.x 200 OK\r\nContent-Type: text/html\r\n'
    body = '<h1>Hello World</h1><img src="doge.gif"/>'
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')


def route_image():
    with open('doge.gif', 'rb') as f:
        header = b'HTTP/1.x 200 OK\r\nContent-Type: image/gif\r\n\r\n'
        img = header + f.read()
        return img


def error(code=404):
    e = {
        404: b'HTTP/1.x 404 Not FOUND\r\n\r\n<h1>NOT FOUND</h1> '
    }
    return e.get(code, b'')


def response_for_path(path):
    r = {
        '/': route_index,
        '/doge.gif': route_image,
    }
    response = r.get(path, error)
    return response


def run(host='', port=3000):
    with socket.socket() as s:
        s.bind((host, port))
        while True:
            s.listen(5)
            sock, addr = s.accept()

            request = sock.recv(1024)
            request = request.decode('utf-8')
            log('ip and request,{}\n{}'.format(addr, request))
            try:
                path = request.split()[1]
                response = response_for_path(path)
                sock.sendall(response)
            except Exception as e:
                log('error', e)
            sock.close()


if __name__ == '__main__':
    config = dict(
        host='',
        port=3000,
    )
    run(**config)

'''
log ip and request, ('127.0.0.1', 7123)
GET / HTTP/1.1
Host: localhost:3000
Connection: keep-alive
sec-ch-ua: "Chromium";v="94", "Google Chrome";v="94", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
'''
